package http

import (
	"net/http"

	"micro-svr/apps/s2/api"
	"micro-svr/apps/s2/internal/model"

	"go-main/library/conf"
	"go-main/library/log"
	"go-main/library/net/http/dam"
)

var svc api.DemoBMServer

// New a bm server.
func New(s api.DemoBMServer) (engine *dam.Engine, err error) {
	var cfg dam.ServerConfig
	if err = conf.Bind("http", &cfg); err != nil {
		return
	}
	svc = s
	engine = dam.NewServer(&cfg)
	api.RegisterDemoBMServer(engine, s)
	initRouter(engine)
	err = engine.Start()
	return
}

func initRouter(e *dam.Engine) {
	e.Ping(ping)
	g := e.Group("/xxx")
	{
		g.GET("/start", howToStart)
	}
}

func ping(ctx *dam.Context) {
	if _, err := svc.Ping(ctx, nil); err != nil {
		log.Error("ping error(%v)", err)
		ctx.AbortWithStatus(http.StatusServiceUnavailable)
	}
}

// example for http request handler.
func howToStart(c *dam.Context) {
	k := &model.ReqHello{
		Hello: "Golang 大法好 !!!",
	}
	c.JSON(k, nil)
}
